package com.example.project.util;


import cn.hutool.core.io.IORuntimeException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Comparator;
import java.util.UUID;

/**
 * 文件操作工具类。
 */

public class FileUtils extends org.apache.commons.io.FileUtils {
    public static void saveFile(InputStream stream, String path) throws IOException {
        // 创建输出流
        FileOutputStream outStream = null;

        try {

            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            outStream = new FileOutputStream(file);

            byte[] bytes = new byte[1024];

            int len = -1;


            while ((len = stream.read(bytes)) != -1) {

                // 写入数据
                outStream.write(bytes, 0, len);
            }

            outStream.flush();

        } finally {

            if (stream != null) {
                stream.close();
            }

            if (outStream != null) {
                outStream.close();
            }

        }

    }

    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            FileUtils.delete(sPath);
            flag = true;
        }
        return flag;
    }
    public static String getFileName(String type) {
        StringBuffer sb = new StringBuffer();
        sb.append(UUID.randomUUID().toString().replaceAll("-",""));
        sb.append(".");
        sb.append(type);
        return sb.toString();
    }

    public static void delete(String path) throws IORuntimeException {

        File file = new File(path);

        //如果路径不存在则终止删除
        if(!file.exists()){
            return;
        }

        try {
            Files.walk(Paths.get(path)).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
        } catch (IOException e) {
            throw new IORuntimeException(MessageFormat.format("删除指定路径：{0}失败", path), e);
        }
    }
}
